import { RCSPOpFile, RCSPOpLargeFileGet } from "../../../lib/rcsp-impl/rcsp"
import { OPFile, OPLargerFileGet } from "../../../jl_lib/jl-rcsp-op/jl_op_watch_1.1.0"

// pages/function_test/large_file_get/index.ts
Page({

    /**
     * 页面的初始数据
     */
    data: {
        pageType: 0,//0：传输，1： 浏览文件
        transferContent: "传输未开始",
        isTransfering: false,
        readFiles: new Array()
    },
    transferContent: "传输未开始",
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(option) {
        const pageType = option.pagetype
        console.log(" pageType  " + pageType);
        this.setData({
            pageType: new Number(pageType).valueOf()
        })
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('acceptDataFromOpenerPage', (data) => {
            console.log(" pageType  " + this.data.pageType);
            if (this.data.pageType == 0) {
                const fileName = data.fileName as string | undefined
                const cluster = data.cluster as number | undefined
                const devIndex = data.devIndex as number | undefined
                if (fileName && cluster && devIndex) {
                    this._startLargeFileGet(fileName, cluster, devIndex)
                }
            }
        })
        this._readdir()
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        RCSPOpLargeFileGet?.cancelGet()
    },
    onShow(){
        this.setData({
            transferContent: this.transferContent
        })
    },
    onHide(){
        RCSPOpLargeFileGet?.cancelGet()
    },
    /**浏览已读取文件*/
    onBrowseFiles() {
        this._readdir()
        this.setData({
            pageType: 1
        })
    },
    onOpreateFile(e: WechatMiniprogram.CustomEvent) {
        const item = e.currentTarget.dataset.item
        const that = this
        const filePath = `${wx.env.USER_DATA_PATH}/readDev/` + item
        return wx.showActionSheet({
            alertText: item,
            itemList: ["删除", "保存文件到手机"],
            success(res) {
                switch (res.tapIndex) {
                    case 0://删除
                        const fs = wx.getFileSystemManager()
                        fs.unlink({
                            filePath: filePath,
                            success: (res) => {
                                that._readdir()
                            },
                            fail: (error) => {
                                console.error("error", error);
                            }
                        })
                        break;
                    case 1://保存文件到手机
                        wx.showModal({
                            title: "导出文件",
                            content: "小程序手机端目前暂不支持保存文件到手机。\n Android端: 请先用其他软件【如:WPS Office】先打开,再保存到手机。\n iOS端：点击右上角菜单转发给微信好友",
                            success: (res) => {
                                if (res.confirm) {
                                    wx.openDocument({
                                        filePath: filePath,
                                        showMenu: true,
                                        fileType: "docx",
                                        success: (res) => {
                                            console.log("打开成功", res);
                                        },
                                        fail: (error) => {
                                            console.error("error", error);
                                        }
                                    })
                                }
                            }
                        })
                        break;
                    default:
                        break;
                }
            }
        })
    },
    _readdir() {
        const fs = wx.getFileSystemManager()
        const that = this
        fs.readdir({
            dirPath: `${wx.env.USER_DATA_PATH}/readDev`,
            success(res) {
                console.log(res.files)
                that.setData({
                    readFiles: res.files
                })
            },
            fail(res) {
                try {
                    fs.mkdirSync(`${wx.env.USER_DATA_PATH}/readDev`, false)
                } catch (e) {
                    console.error(e)
                }
                console.error(res)
            }
        })
    },
    _startLargeFileGet(fileName: string, cluster: number, devIndex: number) {
        if (RCSPOpLargeFileGet?.isFree() == true) {
            let sdCardBean: OPFile.SDCardBean | undefined
            const storageDevs = RCSPOpFile?.getOnLineSdCardBeans()
            if (storageDevs) {
                for (let index = 0; index < storageDevs.length; index++) {
                    const element = storageDevs[index];
                    if (element.devHandler == devIndex) {
                        sdCardBean = element
                        break
                    }
                }
            }
            if (sdCardBean && fileName) {
                const getFileCallback: OPLargerFileGet.TransferTaskCallback = {
                    onError: (code: number) => {
                        console.error("读文件失败，error code : " + code);
                        this.transferContent =  "读取文件失败,code:" + code
                        this.setData({
                            transferContent: this.transferContent ,
                            isTransfering: false
                        })
                    },
                    onStart: () => {
                        console.log("读取文件开始");
                        this.transferContent =  "读取文件开始" 
                        this.setData({
                            transferContent: this.transferContent,
                            isTransfering: true
                        })
                    },
                    onProgress: (progress: number, packectData?: ArrayBuffer) => {
                        console.log("读取文件进度" + progress + " , data size " + packectData?.byteLength);
                        this.transferContent =  "读取文件进度" + progress
                        this.setData({
                            transferContent:  this.transferContent
                        })
                    },
                    onSuccess: (data: ArrayBuffer) => {
                        console.log("读文件成功，" + data.byteLength);
                        const fs = wx.getFileSystemManager()
                        const now = new Date()
                        const hours = now.getHours()
                        const min = now.getMinutes()
                        const second = now.getSeconds()
                        const hourStr = hours > 10 ? ("" + hours) : ("0" + hours)
                        const minutesStr = min > 10 ? ("" + min) : ("0" + min)
                        const secondStr = second > 10 ? ("" + second) : ("0" + second)
                        const date = (now.getFullYear() % 100) + "" + (now.getMonth() + 1) + now.getDate() + "-" + hourStr + minutesStr + secondStr
                        const tempFileName = date + "_" + fileName + ".txt"
                        fs.writeFile({
                            filePath: `${wx.env.USER_DATA_PATH}/readDev/` + tempFileName,
                            data: new Uint8Array(data).buffer,
                            success(res) {
                                console.log(res)
                            },
                            fail(res) {
                                console.error(res)
                            }
                        })
                        this.transferContent="读取文件完成"
                        this.setData({
                            transferContent:  this.transferContent,
                            isTransfering: false
                        })
                    },
                    /**
                     * @param code
                     * 0:主动取消
                     * 1:丢包
                     * 2：crc错误
                    */
                    onCancel: (reason: number) => {
                        this.transferContent= "读取文件取消，reason" + reason
                        this.setData({
                            transferContent:  this.transferContent,
                            isTransfering: false
                        })
                        console.error("读文件取消，reason ：" + reason);
                    }
                }
                if (devIndex == OPFile.SDCardBean.INDEX_FLASH || devIndex == OPFile.SDCardBean.INDEX_FLASH2) {
                    //flash用文件名方式
                    console.log("flash用文件名方式 " + fileName + " ");
                    console.log("flash用文件名方式 ", sdCardBean);
                    RCSPOpLargeFileGet.excuteGetTaskByFileNameAndDevHandle({
                        offset: 0,
                        sdCardBean: sdCardBean,
                        fileName: fileName,
                        callback: getFileCallback
                    })
                    // RCSPOpLargeFileGet.excuteGetTaskByFileName({
                    //     offset: 0,
                    //     fileName: fileName, callback: getFileCallback
                    // })
                } else {//sd卡用簇号方式
                    console.log("sd卡用簇号方式");

                    RCSPOpLargeFileGet.excuteGetTaskByFileCluster({
                        offset: 0,
                        sdCardBean: sdCardBean,
                        cluster: cluster,
                        callback: getFileCallback
                    })
                }
            }
        }
    }
})